import time
from selenium.webdriver.common.action_chains import ActionChains

from Common.basepage import BasePage
from PageLocators.Viplearn.viplearn_home_loc import VipLearnHomePageLocator as vl_loc
from PageObjects.tools import replace_loc


class VipLearnHomePage(BasePage):
    # 打开导航栏
    def vl_click_login(self):
        self.click_element(vl_loc.login_btn_loc, "点击viplearn登录按钮")
        time.sleep(1)
        self.click_element(vl_loc.email_div_loc, "切换邮箱登录")
        time.sleep(1)
        self.click_element(vl_loc.check_img_loc, "切换邮箱登录")

    def vl_click_filter_tab(self, tab_loc):
        self.click_element(tab_loc, "点击搜索tab标签失败")

    def vl_filter(self, filter_loc, *args):
        """
        点击筛选项
        :param filter_loc: 可替换文本的定位元素
        :param args: 要选择的选项文本数组
        :return:
        """

        for text in args:
            try:
                new_loc = replace_loc(filter_loc, text)
                fail_img_text = "点击选择筛选项失败：{}".format(new_loc)
                self.click_element(new_loc, fail_img_text)
            except Exception as e:
                print(e)
        time.sleep(5)
        self.click_element(vl_loc.submit_loc, "点击提交按钮")

    def vl_tab_count(self, count_loc, tab_text):
        """
        :param count_loc: 搜索tab计数定位元素
        :param tab_text: 更换定位元素信息的文本
        :return: 获取到的搜索tab项的计数
        """
        text_count = ""
        try:
            new_count_loc = replace_loc(count_loc, tab_text)
            text_count = self.get_element_text(new_count_loc, "获取tab计数文本失败")
        except:
            pass
        if text_count:
            text_count = text_count.lstrip(' · ')
        return text_count

    def vl_tag_count(self, loc):
        """
        :param loc: 标签定位元素
        :return: 返回该标签元素的数量
        """
        time.sleep(3)
        tags = self.tag_find_elements(loc)
        return len(tags)

    def is_ele_exist(self, loc):
        """判断元素是否存在"""
        return self.is_element_exist(loc)

    def vl_video(self, video_loc=None):
        """html视频播放暂停"""
        video_url = ""
        flag = False
        try:
            # 定位播放的位置
            video = self.get_element(vl_loc.vdieo_loc)
            # 返回文件
            video_url = self.driver.execute_script("return arguments[0].currentSrc;", video)
            print('视频URL：', video_url)

            # 播放视频
            print("开始播放视频。。。")
            self.driver.execute_script("return arguments[0].play()", video)

            # 播放15秒钟
            time.sleep(15)

            # 暂停视频
            print("暂停视频。。。")
            self.driver.execute_script("return arguments[0].pause()", video)

            # 暂停15秒钟
            time.sleep(5)

            # 播放视频
            print("重新播放视频。。。")
            self.driver.execute_script("return arguments[0].play()", video)
            # 播放15秒钟
            time.sleep(15)
            flag = True
        except:
            pass
        return flag, video_url

    def vl_search_name(self, loc, name):
        """搜索框输入， 搜索"""
        self.input_text(loc, "输入教师名字", name)
        self.click_element(vl_loc.search_img_loc, "点击搜索按钮")

    def vl_clear_search(self, loc):
        """清空搜索输入框内容并重新搜索"""
        # 清空输入框内容
        self.clear_data(loc, "清空搜索输入框")
        self.click_element(vl_loc.search_img_loc, "点击搜索按钮")
        time.sleep(3)

    def vl_clear_all(self):
        """清楚所有筛选条件"""
        if self.is_element_exist(vl_loc.clear_loc):
            self.click_element(vl_loc.clear_loc, "点击清除所有筛选项")
        return

    def vl_lst_cv_click_selected(self, loc, img_doc, attribute_name, expectancy_value):
        """点击并判断选中状态"""
        return self.is_click_and_selected(loc, img_doc, attribute_name, expectancy_value)

    def vl_cv_content(self):
        """点击列表简介， 查看详情"""
        text = None
        # 获取文本内容
        if self.is_element_exist(vl_loc.list_teacher_cv_content_loc):
            text = self.get_element_text(vl_loc.list_teacher_cv_content_loc, "获取简介文本")
        if text:
            return True
        else:
            return False

    def vl_switch_window(self):
        """切换窗口"""
        # 获取打开的多个窗口句柄
        handles = self.driver.window_handles
        # 切换到当前最新打开的窗口
        self.driver.switch_to.window(handles[-1])
        current_url = self.driver.current_url
        print("当前窗口URL：", current_url)

    def vl_contact_teacher(self):
        """联系老师用例"""
        self.click_element(vl_loc.contact_teacher_loc, "点击联系老师")
        flag = self.is_element_exist(vl_loc.app_chat_loc)
        self.driver.close()
        self.vl_switch_window()
        return flag

    def vl_select_courses(self, courses_name):
        """
        选择课程
        :param courses_name: 课程名称
        :return:
        """
        flag = True
        msg = "选择课程成功"
        courses_loc = replace_loc(vl_loc.courses_loc, courses_name)
        if self.is_element_exist(courses_loc):
            self.click_element(courses_loc, "预约-选择课程")
        else:
            flag = False
            msg = "未找到课程{}，请先检查用例数据".format(courses_name)
            print(msg)
        self.click_element(vl_loc.next_loc, "选择课程后点击下一步")
        return flag, msg

    def vl_select_lesson(self, lesson_name):
        """
        选择课时
        :param lesson_name: 课时名称
        :return:
        """
        flag = True
        msg = "选择课时成功"
        lesson_loc = replace_loc(vl_loc.courses_loc, lesson_name)
        if self.is_element_exist(lesson_loc):
            self.click_element(lesson_loc, "预约-选择课时")
        else:
            flag = False
            msg = "未找到课时{}，请先检查用例数据".format(lesson_name)
            print(msg)
        self.click_element(vl_loc.next_loc, "选择课时后点击下一步")
        return flag, msg

    def vl_select_class_time(self, time_range, count):
        """
        选择时间
        :param time_range: 上课时间段
        :param count: 日历最多翻页次数
        :return:
        """
        flag = True
        msg = "选择时间成功"
        curriculum_time_loc = replace_loc(vl_loc.curriculum_time_loc, time_range)
        # start_time = time_range.split('-')[0]
        # row_loc = replace_loc(vl_loc.row_loc, start_time)
        # while True:
        #     if self.is_element_exist(row_loc):
        #         break
        #     else:
        #         js = "document.getElementsByClassName('overflow-hidden')[0].scrollTop=10000"
        #         self.driver.execute_script(js)
        #         continue
        time.sleep(3)
        js = "var d=document.getElementsByClassName('max-h-full')[0].scrollTop=10000"
        self.driver.execute_script(js)
        self.driver.execute_script
        for i in range(1, count+1):
            if self.is_element_exist(curriculum_time_loc):
                self.click_element(curriculum_time_loc, "预约-选择课程")
                time.sleep(2)
                self.click_element(vl_loc.next_loc, "选择课程后点击下一步")
                # if self.toast_wait_eleVisible(vl_loc.take_up_toast_loc, "获取选择上课时间已被占用的toast弹窗"):
                #     print(i, "----", self.toast_wait_eleVisible(vl_loc.take_up_toast_loc))
                #     continue
                break
            else:
                self.click_element(vl_loc.right_loc, "课程时间日历翻页")
            if i == count:
                flag = False
                msg = "无可选时间的班级，请更改用例curriculum_time重试"
                print(msg)
        return flag, msg

    def vl_booking_class(self, loc, img_doc, courses_name, lesson_name, time_range, count):
        """
        预约上课
        :param loc: 预约课程元素定位
        :param img_doc:
        :param courses_name: 课程名称
        :param lesson_name: 课时
        :param time_range: 时间段
        :param count: 课表日历最大翻页次数
        :return:
        """
        flag = True
        msg = "选择成功"

        self.click_element(loc, img_doc)
        flag, msg = self.vl_select_courses(courses_name)
        if not flag:
            return flag, msg
        flag, msg = self.vl_select_lesson(lesson_name)
        if not flag:
            return flag, msg
        flag, msg = self.vl_select_class_time(time_range, count)
        return flag, msg

    def wechat_pay(self):
        """微信支付"""
        self.click_element(vl_loc.wechat_pay_loc, "选择微信支付")
        time.sleep(5)
        # 判断是否选中
        try:
            v = self.get_element_attribute(vl_loc.wechat_checked_loc, "src", "获取微信支付选中状态")
            if "checked" in v:
                self.click_element(vl_loc.pay_loc, "选中微信，点击支付按钮")
                time.sleep(5)
                if self.is_element_exist(vl_loc.wechat_qrcode_loc):
                    time.sleep(5)
                    self.move_relative_position_click(vl_loc.wechat_qrcode_loc)
                    # self.click_element(vl_loc.message_loc, "点击空白处")
                    time.sleep(15)
                    self.click_element(vl_loc.close_paying_loc, "关闭微信支付二维码")
                    return True
        except:
            return False

    def balance_pay(self):
        """可用余额支付"""
        time.sleep(5)
        self.click_element(vl_loc.balance_loc, " 选中可用余额")
        v = self.get_element_attribute(vl_loc.balance_checked_loc, "src", "获取微信支付选中状态")
        if "checked" in v:
            self.click_element(vl_loc.pay_loc, "选可用余额支付后点击支付")
            time.sleep(1)
            self.click_element(vl_loc.check_order_loc, "可用余额支付后点击弹窗-查看订单")
            time.sleep(3)
        self.vl_switch_window()
        count = self.vl_tag_count(vl_loc.await_order_list_card)
        print("等待列表数据共有{}个".format(count))
        return count

    def cancel_await_order(self):
        """终止等待列表订单"""
        time.sleep(10)
        self.click_element(vl_loc.termination_order_loc, "终止订单")
        time.sleep(3)
        self.click_element(vl_loc.termination_affirm_loc, "确认终止")
        time.sleep(3)
        if self.vl_tag_count(vl_loc.await_order_list_card) == 0:
            return "取消订单成功"

    def vl_pay(self):
        """支付"""
        # wechat_verify = "微信支付验证通过" if self.wechat_pay() else "微信支付验证失败"
        # print(wechat_verify)
        await_count = self.balance_pay()
        cancel_msg = self.cancel_await_order()
        return await_count, cancel_msg

    def vl_go_to_page(self, loc, img_doc, subpage_head_loc):
        """
        从头像下拉选择进入功能页
        :param loc: 头像悬浮
        :param img_doc: 点击描述（截图保存名称）
        :param subpage_head_loc: 子页面头部标识，断言用
        :return: 子页面subpage_head_loc文本内容
        """
        self.mouse_suspension(vl_loc.head_set_loc, "悬浮头像处")
        time.sleep(1)
        self.click_element(loc, img_doc)
        time.sleep(5)
        try:
            text = self.get_element_text(subpage_head_loc, "获取功能页面的头部标识文本")
        except:
            text = None
        return text

    def vl_record_order(self, loc, img_doc, card, cards):
        """预约记录、我的订单"""
        self.click_element(loc, img_doc)
        time.sleep(5)
        count = self.vl_tag_count(card)
        # 第一条card文本
        try:
            text = self.get_element_text(card, img_doc)
        except:
            text = ""
        # 页面文本
        # try:
        #     text = self.get_element_text(cards, img_doc)
        # except:
        #     text = ""
        tab = "【" + img_doc.split('-')[1] + "tab】下列表的第一页数据数量为："
        print(tab, count)
        return count, text

    def vl_wallet_deal_detail(self, option):
        """我的钱包-交易详情"""
        self.click_element(vl_loc.dealType_select_loc, "点击选择交易类型输入框")
        option_loc = replace_loc(vl_loc.dealType_option_loc, option)
        self.click_element(option_loc, "点击交易类型--{}".format(option))
        time.sleep(1)
        self.click_element(vl_loc.wallet_search_loc, "点击搜索交易详情")
        time.sleep(5)
        data = self.get_element_text(vl_loc.deal_detail_tbody_loc, "搜索-获取交易详情搜索结果")
        return data

    def vl_wallet_reset(self):
        """我的钱包-交易详情--重置"""
        self.click_element(vl_loc.wallet_reset_loc, "点击交易详情重置按钮")
        time.sleep(5)
        data = self.get_element_text(vl_loc.deal_detail_tbody_loc, "重置-获取交易详情搜索结果")
        return data

    def vl_my_homepage(self):
        """我的主页-个人信息&账号管理"""
        data = {}
        try:
            username = self.get_element_text(vl_loc.pd_username_loc, "我的主页个人信息用户名")
        except:
            username = None
        try:
            invitation_code = self.get_element_text(vl_loc.pd_invitation_code_loc, "我的主页个人信息邀请码")
        except:
            invitation_code = None
        self.click_element(vl_loc.account_management_loc, "点击我的主页-账号管理")
        time.sleep(2)
        try:
            email = self.get_element_text(vl_loc.am_email_loc, "我的主页账号管理电子邮箱")
        except:
            email = None
        try:
            mobile = self.get_element_text(vl_loc.am_mobile_loc, "我的主页账号管理手机号码")
        except:
            mobile = None
        data["username"] = username
        data["invitation_code"] = invitation_code
        data["email"] = email
        data["mobile"] = mobile
        return data

    def vl_logout(self):
        """退出登录"""
        text = self.vl_go_to_page(vl_loc.quit_loc, "退出登录", vl_loc.login_btn_loc)
        return text
